package com.hmdp.service.impl;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.CacheClient;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.RedisData;
import com.hmdp.utils.SystemConstants;
import io.netty.util.internal.StringUtil;
import lombok.AllArgsConstructor;
import lombok.NonNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.GeoResult;
import org.springframework.data.geo.GeoResults;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.domain.geo.GeoReference;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private CacheClient cacheClient;
    @Autowired
    private IShopService shopService;

    @Override
    public Result queryById(Long id) {
//        //1.从redis查询商铺缓存
//        String shopJson = stringRedisTemplate.opsForValue().get(RedisConstants.CACHE_SHOP_KEY + id);
//        //2.判断是否存在
//      if(!StringUtils.isEmpty(shopJson)){
//          //3.存在，返回redis中的信息
//          Shop shop = JSONUtil.toBean(shopJson, Shop.class);
//          return Result.ok(shop);
//      }
//      //判断命中是否是空值,如果是空值的话，就证明该对象在数据库中也不存在
//        //不等于null，那就是空值
//        if(shopJson!=null){
//            //返回一个错误信息
//            return Result.fail("店铺不存在");
//        }
//
//        //4.不存在,根据id去数据库进行查询
//        Shop shop = this.getById(id);
//       //TODO 将空值写进redis，不然有可能会有缓存穿透的风险啊
//        if(ObjectUtils.isEmpty(shop)){
//            //5.不存在，返回商铺不存在信息
//          stringRedisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_KEY+id,"",RedisConstants.CACHE_NULL_TTL,TimeUnit.MINUTES);
//            return Result.fail("店铺不存在");
//        }
//        //6.存在，将数据写入redis
//        //转成json格式进行写入
//        String jsonStr = JSONUtil.toJsonStr(shop);
//        stringRedisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_KEY+id,jsonStr,RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);
//        //7.然后进行数据返回
//
//        return Result.ok(shop);


        //用返回空字符串解决缓存穿透
        // Shop shop = queryWithPassThrough(id);
        //用封装空字符串的方法解决缓存穿透问题
//        Shop shop = cacheClient.queryWithPassThrough(RedisConstants.CACHE_SHOP_TTL, TimeUnit.SECONDS, RedisConstants.CACHE_SHOP_KEY, id, Shop.class, id2 -> getById(id2));
        //用互斥锁解决缓存击穿
        //Shop shop=queryWithMutex(id);
        //用逻辑过期解决缓存击穿
        Shop shop = queryWithLogicalExpire(id);
        if(shop==null){
            return Result.fail("店铺不存在");
        }
        return Result.ok(shop);
    }

    public Shop queryWithLogicalExpire(Long id){
        //1.从redis查询商铺缓存
        String shopJson = stringRedisTemplate.opsForValue().get(RedisConstants.CACHE_SHOP_KEY + id);
        //2.如果未命中，返回空
        if(StringUtil.isNullOrEmpty(shopJson)){
            return null;
        }
        //3.如果命中，需要判断缓存是否过期
        RedisData redisData = JSONUtil.toBean(shopJson, RedisData.class);
        //4.判断是否过期
        Shop shop = JSONUtil.toBean((JSONObject) redisData.getData(), Shop.class);
        LocalDateTime expireTime = redisData.getExpireTime();
        if(expireTime.isAfter(LocalDateTime.now())){
            //如果是在当前时间之后，证明还没有过期
            //直接返回旧数据
            return shop;

        }
        //走到这证明已经过期,首先先获取互斥锁
        boolean islock = tryLock(RedisConstants.LOCK_SHOP_KEY + id);
        //获取锁成功
        if(islock){
           //需要开启独立的线程，实现缓存重建
            CACHE_REBUID_EXECUTOR.submit(()->{
                try {
                    //重建缓存
                    this.saveShop2Redis(id,20L);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }finally {
                    unlock(RedisConstants.LOCK_SHOP_KEY+id);
                }
                //重建缓存后需要释放锁

            });
        }
        return shop;

    }
    //创建线程池
    private static final ExecutorService CACHE_REBUID_EXECUTOR= Executors.newFixedThreadPool(10);

    /**
     * 用互斥锁解决redis的缓存击穿
     * 成功获取到的锁才去查询数据库，否则等待
     * @param id
     * @return
     */
    public Shop queryWithMutex(Long id) {
        //1.从redis查询商铺缓存
        String shopJson = stringRedisTemplate.opsForValue().get(RedisConstants.CACHE_SHOP_KEY + id);
        //2.判断是否存在
        if(!StringUtil.isNullOrEmpty(shopJson)){
            //3.存在，返回redis中的信息
            Shop shop = JSONUtil.toBean(shopJson, Shop.class);
            return shop;
        }
        //判断命中是否是空值,如果是空值的话，就证明该对象在数据库中也不存在
        //不等于null，那就是空值
        if(shopJson!=null){
            //返回一个错误信息
            return null;
        }

        //4.不存在,获取互斥锁

        Shop shop = null;
        try {
            boolean isLock = tryLock(RedisConstants.LOCK_SHOP_KEY+id);
            //4.1判断是否获取成功
            if(!isLock){
                //4.2获取失败，则休眠并重试
                Thread.sleep(50);
                return queryWithMutex(id);
            }

            //4.3成功，根据id查询数据库
            shop = this.getById(id);
            //TODO 将空值写进redis，不然有可能会有缓存穿透的风险啊
            if(ObjectUtils.isEmpty(shop)){
                //5.不存在，返回商铺不存在信息
                stringRedisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_KEY+id,"",RedisConstants.CACHE_NULL_TTL,TimeUnit.MINUTES);
                return null;
            }
            //6.存在，将数据写入redis
            //转成json格式进行写入
            String jsonStr = JSONUtil.toJsonStr(shop);
            stringRedisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_KEY+id,jsonStr,RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);
        } catch (InterruptedException e) {
           throw new RuntimeException(e);
        } finally {
            unlock(RedisConstants.LOCK_SHOP_KEY+id);
        }
        //7.然后进行数据返回
        //释放互斥锁

        return shop;
    }

    /**
     * 解决缓存穿透的方法，使用缓存空字符串的方法
     * @param id
     * @return
     */
     public Shop queryWithPassThrough(Long id){
         //1.从redis查询商铺缓存
         String shopJson = stringRedisTemplate.opsForValue().get(RedisConstants.CACHE_SHOP_KEY + id);
         //2.判断是否存在
         if(!StringUtils.isEmpty(shopJson)){
             //3.存在，返回redis中的信息
             Shop shop = JSONUtil.toBean(shopJson, Shop.class);
             return shop;
         }
         //判断命中是否是空值,如果是空值的话，就证明该对象在数据库中也不存在
         //不等于null，那就是空值
         if(shopJson!=null){
             //返回一个错误信息
             return null;
         }

         //4.不存在,根据id去数据库进行查询
         Shop shop = this.getById(id);
         //TODO 将空值写进redis，不然有可能会有缓存穿透的风险啊
         if(ObjectUtils.isEmpty(shop)){
             //5.不存在，返回商铺不存在信息
             stringRedisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_KEY+id,"",RedisConstants.CACHE_NULL_TTL,TimeUnit.MINUTES);
             return null;
         }
         //6.存在，将数据写入redis
         //转成json格式进行写入
         String jsonStr = JSONUtil.toJsonStr(shop);
         stringRedisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_KEY+id,jsonStr,RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);
         //7.然后进行数据返回

         return shop;
}

    /**
     * 根据商品id给商品设置逻辑过期时间(解决缓存击穿问题)
     * @param id
     * @param expireSeconds
     */
     public void saveShop2Redis(Long id,Long expireSeconds){
         //1.查询店铺数据
         Shop shop = this.getById(id);
         //2.封装逻辑过期时间
         RedisData redisData=new RedisData();
         redisData.setData(shop);
         redisData.setExpireTime(LocalDateTime.now().plusSeconds(expireSeconds));
         //3.写入redis
         stringRedisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_KEY+id,JSONUtil.toJsonStr(redisData));
     }
    /**
     * 尝试获取锁方法
     * @param key 锁的名称
     * @return
     */
    private boolean tryLock(String key){
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(flag);
    }

    /**
     * 释放锁的方法
     * @return
     */
    public void unlock(String key){
        stringRedisTemplate.delete(key);
    }
    @Transactional
    @Override
    public Result updateByDetail(Shop shop) {
        Long id = shop.getId();
        if(id==null){
            return Result.fail("店铺id不能为空");
        }
        //1.更新数据库
        this.updateById(shop);
        //2.删除缓存
        stringRedisTemplate.delete(RedisConstants.CACHE_SHOP_KEY+shop.getId());
        return Result.ok();
    }

    @Override
    public Result querShopByType(Integer typeId, Integer current, Double x, Double y) {
        //判断是否需要坐标查询
        if(x==null||y==null){
            // 根据类型分页查询
            Page<Shop> page = shopService.query()
                    .eq("type_id", typeId)
                    .page(new Page<>(current, SystemConstants.DEFAULT_PAGE_SIZE));
            // 返回数据
            return Result.ok(page.getRecords());
        }

        //计算分页参数
        //从哪开始
        int form=(current-1)*SystemConstants.DEFAULT_PAGE_SIZE;
        //到哪结束
        int end=current*SystemConstants.DEFAULT_PAGE_SIZE;

        //查询redis，按照距离排序、分页 结果：shopId,distance
        GeoResults<RedisGeoCommands.GeoLocation<String>> results = stringRedisTemplate.opsForGeo()
                .search(RedisConstants.SHOP_GEO_KEY + typeId, GeoReference.fromCoordinate(x, y),
                        new Distance(5000),
                        RedisGeoCommands.GeoSearchCommandArgs.newGeoSearchArgs().includeDistance().limit(end)
                );
        //解析id
        if(results==null){
            return Result.ok(Collections.emptyList());
        }
        List<GeoResult<RedisGeoCommands.GeoLocation<String>>> list = results.getContent();
        if(list.size()<form){
            return Result.ok(Collections.EMPTY_LIST);
        }
        //截取from-end的部分
        List<Long> ids=new ArrayList<>(list.size());
        Map<String,Distance> distanceMap=new HashMap<>(list.size());
        list.stream().skip(form).forEach(e->{
            //获取店铺id
            String name = e.getContent().getName();
            ids.add(Long.valueOf(name));
            //获取距离
            @NonNull Distance distance = e.getDistance();
            distanceMap.put(name,distance);
        });
        List<Shop> shops=new ArrayList<>();
        //根据id查询shop
        for (Long id : ids) {
            Shop shop = shopService.getById(id);
            shops.add(shop);
            Distance distance = distanceMap.get(shop.getId().toString());
            shop.setDistance(distance.getValue());
        }
        //
        return Result.ok(shops);
    }
}
